package com.jielin.handling.controller.videoclip;

import com.jielin.handling.Annotation.MyPower;
import com.jielin.handling.entity.vo.VideoClipVo;
import com.jielin.handling.util.SecuritySHA1Utils;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chenzhang
 * @date 2019/10/14 - 13:37
 */
@CrossOrigin
@RestController
@RequestMapping("/videoClip/")
@Slf4j
@MyPower(name = "视频剪辑模块", url = "/videoClip")
public class VideoClipController {

    @RequestMapping("getAjaxJson")
    public VideoClipVo getAjaxJson(HttpServletRequest request, HttpServletResponse response) {
        VideoClipVo j = new VideoClipVo();
        String url = "https://zenvideo.cn/open_platform/create_user/";//调用sendPost方法时传入的外网接口地址
        Map<String, String> params = new HashMap<String, String>();//调用sendPost方法时传入外网接口地址携带的参数

        //String stringSignTemp = "app_id=e7726415&signature=e&time=1570982400&user_id=18271827495";//对参数按照参数名ASCII字典序排序, 按照格式拼接成字符串
        // abcabcabc app_ide7726415time1570982400user_id18271827495 abcabcabc
        //String stringSignTemp="abcabcabc  app_ide7726415 time1512345678  abcabcabc";
        params.put("app_id", "e7726415");
        Date date = new Date();
        Timestamp ts = new Timestamp(date.getTime());
        String time = String.valueOf((ts.getTime()) / 1000);
        params.put("time", time);
        String secret = "60e2663634f94dd39bd908099387882f";//API秘钥
        String stringSignTemp = secret + "app_ide7726415" + "time" + time + secret;
        try {
            String signature = SecuritySHA1Utils.shaEncode(stringSignTemp);
            params.put("signature", signature);
            //String signature = SecuritySHA1Utils.shaEncode(stringSignTemp);
            //System.out.println(signature);
            String orgInfo = sendPost(url, params);
            JSONObject obj = JSONObject.fromObject(orgInfo);
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("code", obj.get("code"));//从接口的数据中取出state值并传入json中
            m.put("message", obj.get("message"));
            m.put("user_id", obj.get("user_id"));
            j.setAttributes(m);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("创建失败");
        }
        return j;
    }

    @RequestMapping("getProjectId")//第三方平台创建智影工程获取ProjectId
    public Map  getProjectId(HttpServletRequest request, HttpServletResponse response) {
        VideoClipVo j = new VideoClipVo();
        String url = "https://zenvideo.cn/open_platform/create_project/";//调用sendPost方法时传入的外网接口地址
        Map<String, String> params = new HashMap<String, String>();//调用sendPost方法时传入外网接口地址携带的参数
        Date date = new Date();
        Timestamp ts = new Timestamp(date.getTime());
        String time = String.valueOf((ts.getTime()) / 1000);

//        params.put("method","method");
//        params.put("arguments","arguments");
//        params.put("customer_data","customer_data");
//        params.put("ratio","ratio");
        String secret = "60e2663634f94dd39bd908099387882f";//API秘钥
        String user_id = "PARTNER__武汉杰霖科技_51_TPGV25";
        String app_id = "e7726415";
        String stringSignTemp = secret + "app_id" + app_id + "time" + time + "titletitle" + "user_id" + user_id + secret;
        //String stringSignTemp="60e2663634f94dd39bd908099387882fapp_ide7726415"+"time"+time+"titletitleuser_idPARTNER__武汉杰霖科技_51_TPGV2560e2663634f94dd39bd908099387882f";
        Map m=null;
        try {
            String signature = SecuritySHA1Utils.shaEncode(stringSignTemp);
            System.out.println(signature);
            params.put("app_id", app_id);
            params.put("signature", signature);
            params.put("time", time);
            params.put("user_id", user_id);
            params.put("title", "title");
            String orgInfo = sendPost(url, params);
            JSONObject obj = JSONObject.fromObject(orgInfo);
            m = new HashMap<String, Object>();
            m.put("code", obj.get("code"));//从接口的数据中取出state值并传入json中
            m.put("message", obj.get("message"));
            m.put("project_id", obj.get("project_id"));
            m.put("app_id", app_id);
            String stringSignTemp2 = secret + "app_id" + app_id+ "project_id" + obj.get("project_id") + "time" + time  + "user_id" + user_id + secret;
            String signature2 = SecuritySHA1Utils.shaEncode(stringSignTemp2);
            m.put("signature", signature2);
            m.put("time", time);
            m.put("user_id", user_id);
            j.setAttributes(m);
            //getPage(request, response, user_id, (String) obj.get("project_id"), time, app_id,secret);
        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("创建失败");
        }
        return m;
    }

    @RequestMapping("getPage")
    public String getPage(HttpServletRequest request, HttpServletResponse response, String user_id, String project_id, String time,  String app_id,String secret) {
        VideoClipVo j = new VideoClipVo();
        Map<String, String> params = new HashMap<String, String>();//调用sendPost方法时传入外网接口地址携带的参数
        params.put("user_id", user_id);
        params.put("project_id", project_id);
        params.put("time", time);
        String stringSignTemp = secret + "app_id" + app_id+ "project_id" + project_id + "time" + time  + "user_id" + user_id + secret;
        String orgInfo="";
        try {
            String signature = SecuritySHA1Utils.shaEncode(stringSignTemp);
            System.out.println(signature);
            params.put("signature", signature);
            String url = "https://zenvideo.cn/open_platform/edit_project/?app_id=" + app_id + "&signature=" + signature + "&time=" + time + "&user_id=" + user_id + "&project_id=" + project_id;//调用sendPost方法时传入的外网接口地址
            orgInfo = sendGet(url, params);
//            JSONObject obj = JSONObject.fromObject(orgInfo);
//            Map<String, Object> m = new HashMap<String, Object>();
//            //m.put("state", obj.get("state"));//从接口的数据中取出state值并传入json中
//            // m.put("data", obj.get("data"));
//            m.put("orgInfo", orgInfo);
//            j.setAttributes(m);

        } catch (Exception e) {
            j.setSuccess(false);
            j.setMsg("查询失败");
        }
        return orgInfo;
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url    发送请求的 URL
     * @param params 请求的参数集合
     * @return 远程资源的响应结果
     */
    private String sendPost(String url, Map<String, String> params) {
        OutputStreamWriter out = null;
        BufferedReader in = null;
        StringBuilder result = new StringBuilder();
        try {
            URL realUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // POST方法
            conn.setRequestMethod("POST");
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.connect();
            // 获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            // 发送请求参数
            if (params != null) {
                StringBuilder param = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (param.length() > 0) {
                        param.append("&");
                    }

                    param.append(entry.getKey());

                    param.append("=");
                    param.append(entry.getValue());
                    System.out.println(entry.getKey() + ":" + entry.getValue());
                }
                System.out.println("param:" + param.toString());
                out.write(param.toString());
            }
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result.toString();
    }

    /**
     * 带参数的get请求
     *
     * @param url
     * @param params
     * @return String
     */
    public static String sendGet(String url, Map<String, String> params) {
// 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
// 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (params != null) {
                for (String key : params.keySet()) {
                    builder.addParameter(key, params.get(key));
                }
            }
            URI uri = builder.build();
// 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
// 执行请求
            response = httpclient.execute(httpGet);
// 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
}
